package org.ysling.litemall.wx.web;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import lombok.extern.slf4j.Slf4j;
import org.ysling.litemall.core.utils.JacksonUtil;
import org.ysling.litemall.core.utils.response.ResponseUtil;
import org.ysling.litemall.core.validator.Order;
import org.ysling.litemall.core.validator.Sort;
import org.ysling.litemall.db.service.*;
import org.ysling.litemall.wx.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.ysling.litemall.db.domain.LitemallComment;
import org.ysling.litemall.db.domain.LitemallGoods;
import org.ysling.litemall.db.domain.LitemallTopic;

import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 专题服务
 */
@Slf4j
@RestController
@RequestMapping("/wx/topic")
@Validated
public class WxTopicController {

    @Autowired
    private LitemallTopicService topicService;
    @Autowired
    private LitemallGoodsService goodsService;
	@Autowired
	private LitemallCollectService collectService;
    @Autowired
    private LitemallCommentService commentService;
    @Autowired
    private LitemallUserService userService;

    /**
     * 专题列表
     *
     * @param page 分页页数
     * @param limit 分页大小
     * @return 专题列表
     */
    @GetMapping("list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallTopic> topicList = topicService.queryList(page, limit, sort, order);
        return ResponseUtil.okList(topicList);
    }

    /**
     * 专题详情
     *
     * @param id 专题ID
     * @return 专题详情
     */
    @GetMapping("detail")
    public Object detail(@LoginUser Integer userId, @NotNull Integer id) {
        LitemallTopic topic = topicService.findById(id);
        List<LitemallGoods> goods = new ArrayList<>();
        for (Integer i : topic.getGoods()) {
            LitemallGoods good = goodsService.findByIdVO(i);
            if (null != good) goods.add(good);
        }
        
		// 用户收藏
		int userHasCollect = 0;
		if (userId != null) userHasCollect = collectService.count(userId, (byte)1, id);

        Map<String, Object> entity = new HashMap<String, Object>();
        entity.put("topic", topic);
        entity.put("goods", goods);
        entity.put("userHasCollect", userHasCollect);
        return ResponseUtil.ok(entity);
    }

    /**
     * 发表评论
     *
     * @param userId  用户ID
     * @param body 评论内容
     * @return 发表评论操作结果
     */
    @PostMapping("comment")
    public Object comment(@LoginUser Integer userId, @RequestBody String body) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }

        Integer valueId = JacksonUtil.parseInteger(body, "valueId");
        String content = JacksonUtil.parseString(body, "content");
        Short star = JacksonUtil.parseShort(body, "star");
        Boolean hasPicture = JacksonUtil.parseBoolean(body, "hasPicture");
        String[] picUrls = JacksonUtil.parseObject(body, "picUrls", String[].class);

        if (valueId == null){
            return ResponseUtil.badArgument();
        }

        if (star == null || star < 0 || star > 5) {
            return ResponseUtil.badArgumentValue();
        }

        if (topicService.findById(valueId) == null) {
            return ResponseUtil.badArgumentValue();
        }

        if (hasPicture == null || !hasPicture) {
            picUrls = new String[0];
        }

        LitemallComment comment = new LitemallComment();
        comment.setType((byte)1);
        comment.setContent(content);
        comment.setStar(star);
        comment.setValueId(valueId);
        comment.setHasPicture(hasPicture);
        comment.setPicUrls(picUrls);
        comment.setUserId(userId);

        //保存评论
        commentService.save(comment);

        return ResponseUtil.ok(comment);
    }

    /**
     * 相关专题
     *
     * @param id 专题ID
     * @return 相关专题
     */
    @GetMapping("related")
    public Object related(@NotNull Integer id) {
        List<LitemallTopic> topicRelatedList = topicService.queryRelatedList(id, 0, 4);
        return ResponseUtil.okList(topicRelatedList);
    }
}